package com.king.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.king.common.lang.Consts;
import com.king.im.vo.IMMessage;
import com.king.im.vo.IMUser;
import com.king.service.ChatService;
import com.king.shiro.AccountProfile;
import com.king.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service("chatService")
public class ChatServiceImpl implements ChatService {
    @Autowired
    RedisUtil redisUtil;

    @Override
    public IMUser getCurrentUser() {
        IMUser user = new IMUser();
        AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        if(profile!=null){//登录用户
            user.setId(profile.getId());
            user.setUsername(profile.getUsername());
            user.setAvatar(profile.getAvatar());
            user.setSign(profile.getSign());
            user.setStatus(IMUser.STATUS_ONLINE);
        }else{//匿名用户
            Long imUserId = (Long) SecurityUtils.getSubject().getSession().getAttribute("imUserId");
            SecurityUtils.getSubject().getSession().setAttribute("imUserId",imUserId);

            user.setId(imUserId != null?imUserId: RandomUtil.randomLong());
            user.setUsername("匿名用户");
            user.setAvatar("http://tp1.sinaimg.cn/5619439268/180/40030060651/1");
            user.setSign("Never Give Up!");
            user.setStatus(IMUser.STATUS_ONLINE);
        }

        return user;
    }

    @Override
    public void setGroupHistoryMsg(IMMessage responseMessage) {
        redisUtil.lSet(Consts.IM_GROUP_HISTROY_MSG_KEY,responseMessage,24*60*60);
    }

    @Override
    public List<Object> getGroupHistoryMsg(int count) {
        long length = redisUtil.lGetListSize(Consts.IM_GROUP_HISTROY_MSG_KEY);
        return redisUtil.lGet(Consts.IM_GROUP_HISTROY_MSG_KEY,length - count<0?0:(length-count),length);
    }
}
